package dao;

import common.Answer;
import common.FileRedefined;
import common.Homework;
import util.StreamUtils;

import java.io.FileInputStream;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class GetStuHW {
    //获取学生作业
    private static Connection conn=DataBaseConnect.getConn();
    private static String sql1="select id,homeworkid,content,file_name,file_path,pic_name,pic_path,question from answer where homeworkid = ?;";
    private static String sql2="select id,student_name,student_number,score from homework where assignmentid=? and studentid=?;";
    private static PreparedStatement pstmt1,pstmt2;
    static {
        try {
            pstmt1=conn.prepareStatement(sql1);
            pstmt2=conn.prepareStatement(sql2);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
    //依据作业号和学号查询某学生的作业
    public static Homework getStuHW (String assignmentid,String studentid){
        try {
            pstmt2.setString(1,assignmentid);
            pstmt2.setString(2,studentid);
            ResultSet rs1= pstmt2.executeQuery();
            if(rs1==null){
                //学生未完成id为assignmentid的作业
                return null;
            }
            while (rs1.next()){
                Homework homework=new Homework(rs1.getString(1),assignmentid,studentid,rs1.getString(3), rs1.getNString(2), rs1.getNString(4));
                pstmt1.setString(1,rs1.getString(1));
                ResultSet rs2=pstmt1.executeQuery();
                while(rs2.next()){
                    FileRedefined file=null;
                    FileRedefined pic=null;
                    if(!rs2.getString(5).isEmpty())
                        file=new FileRedefined(rs2.getString(4), StreamUtils.streamToByteArray(new FileInputStream(rs2.getString(5))));
                    if(!rs2.getString(7).isEmpty())
                        pic=new FileRedefined(rs2.getString(6),StreamUtils.streamToByteArray(new FileInputStream(rs2.getString(7))));
                    Answer answer=new Answer(rs2.getString(1),rs2.getString(2),rs2.getString(3),pic,file,rs2.getString(8));
                    homework.getAnswers().add(answer);
                }
                return homework;
            }
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("获取学生作业失败");
        }
        return null;
    }
}
